#include "FileTableDelegate.h"
#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtGui/QTableView>
#include "FileTableModel.h"

FileTableDelegate::FileTableDelegate(QTableView* tableView,QObject *parent)
	: QItemDelegate(parent),_tableView(tableView)
{

}

FileTableDelegate::~FileTableDelegate()
{

}

void FileTableDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const{
	QSize size = index.model()->data(index,Qt::SizeHintRole).toSize();
	if(_tableView){
		_tableView->setColumnWidth(index.column(),size.width());
		_tableView->setRowHeight(index.row(),size.height());
	}
	QItemDelegate::paint(painter, option, index);
	QImage image = index.model()->data(index, Qt::DisplayRole).value<QImage>();
	if(!image.isNull()){
		if (image.width()>size.width() || image.height()>size.height()){
			image=image.scaled(size,Qt::KeepAspectRatio);
		}
		QRect rect(getImageRect(QRect(option.rect.topLeft(),size),image.rect()));
		painter->drawImage(rect,image/*,image.rect()*/);
		painter->setPen(QColor(Qt::black));
		painter->drawRect(rect);
	}

	if (index.model()->data(index,FileTableModel::MarkRole).toBool()){
		static QImage signedImg(":/imgs/signed.PNG");
		painter->drawImage(option.rect.topLeft()+=QPoint(1,1),signedImg);
	}

}

QRect FileTableDelegate::getImageRect(const QRect& cellRect,const QRect& imageRect) const{
	int cellWidth = cellRect.width();
	int imageWidth  = imageRect.width();
	int cellHeight = cellRect.height();
	int imageHeight = imageRect.height();
	//int width=0;
	//int height=0;
	//if (imageWidth > imageHeight){
	//	width = imageWidth > cellWidth?cellWidth:imageWidth;
	//	height = width*imageHeight/imageWidth;
	//	//width=cellRect.width();
	//	//height=imageRect.height()*cellRect.height()/imageRect.width();
	//}else{
	//	height = imageHeight > cellHeight?cellHeight:imageHeight;
	//	width = height*imageWidth/imageHeight;
	//	//width=imageRect.width()*cellRect.width()/imageRect.height();
	//	//height=cellRect.height();
	//}
	QRect targetRect(cellRect.x()+(cellWidth-imageWidth)/2,cellRect.y()+(cellHeight-imageHeight)/2,imageWidth,imageHeight);
	return targetRect.adjusted(2,2,-4,-4);
}
